import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import { Role } from "../router/types";

export interface UserState {
  // 用户信息
  id: string | null;
  username: string | null;
  roles: Role[];
  permissions: string[];
  avatar?: string;
  email?: string;
  lastLogin?: Date;

  // 认证状态
  isAuthenticated: boolean;
  token: string | null;

  // 方法
  setUser: (user: Partial<UserState>) => void;
  updateUser: (userData: Partial<UserState>) => void;
  clearUser: () => void;
}

// 初始状态
const initialState = {
  id: null,
  username: null,
  roles: [],
  permissions: [],
  isAuthenticated: false,
  token: null,
};

// 创建持久化存储
export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      // 初始状态
      ...initialState,

      // 设置用户（登录时使用）
      setUser: (user) =>
        set((state) => ({
          ...state,
          ...user,
          isAuthenticated: true,
          lastLogin: new Date(),
        })),

      // 更新用户（部分更新）
      updateUser: (userData) =>
        set((state) => ({
          ...state,
          ...userData,
        })),

      // 清除用户（登出时使用）
      clearUser: () => set(initialState),
    }),
    {
      name: "user-storage", // localStorage中的键名
      storage: createJSONStorage(() => localStorage), // 使用localStorage
      partialize: (state) => ({
        // 选择需要持久化的字段
        id: state.id,
        username: state.username,
        roles: state.roles,
        permissions: state.permissions,
        avatar: state.avatar,
        email: state.email,
        isAuthenticated: state.isAuthenticated,
        token: state.token,
        lastLogin: state.lastLogin,
      }),
    }
  )
);
